$(function() {

    $(".form-myt-purchase-purchase-receipt-inputBasic") .data("formOptions", {
        updateTotalAmount : function() {
            var $form = $(this);
            var $grid = $form.find(".grid-myt-purchase-purchase-receipt-inputBasic");
            var userData = {
                "commodity.display" : "合计："
            };
            // 更新表格汇总统计数据
            userData.quantity = $grid.jqGrid('sumColumn', 'quantity');
            userData.amount = $grid.jqGrid('sumColumn', 'amount');
            userData.deliveryAmount = $grid.jqGrid('sumColumn', 'deliveryAmount');
            userData.roadAmount = $grid.jqGrid('sumColumn', 'roadAmount');
            userData.discountAmount = $grid.jqGrid('sumColumn', 'discountAmount');
            userData.costAmount = $grid.jqGrid('sumColumn', 'costAmount');
            $grid.jqGrid("footerData", "set", userData, true);

            $form.setFormDatas({
                amount : userData.amount,
                totalDeliveryAmount : userData.deliveryAmount,
                totalDiscountAmount : userData.discountAmount,
                totalRoadAmount : userData.roadAmount,
                totalCostAmount : userData.costAmount
            });
        },
        updateTotalAccountAmount : function() {
            var $form = $(this);
            var $grid = $form.find(".grid-myt-purchase-purchase-receipt-inputBasic-accountSubjects");
            var userData = {
                "accountSubject.display" : "合计："
            };

            var ids = $grid.jqGrid("getDataIDs");
            var sum1 = 0;
            var sum2 = 0;
            var sum = 0;
            var supplierId = $form.find("select[name='supplier.id']").val();
            $.each(ids, function(i, id) {
                var rowdata = $grid.jqGrid("getRowData", id);
                var bizTradeUnitId = rowdata['tradeReceipt.bizTradeUnit.id'].split("_")[1];
                if (bizTradeUnitId != supplierId) {
                    if (rowdata['costable'] == 'true') {
                        sum1 = MathUtil.add(sum1, rowdata['amount']);
                    } else {
                        sum2 = MathUtil.add(sum2, rowdata['amount']);
                    }
                } else {
                    rowdata['costable'] = 0;
                    $grid.jqGrid('setRowData', id, rowdata);
                }
                sum = MathUtil.add(sum, rowdata['amount']);
            });
            userData.amount = sum;
            $grid.jqGrid("footerData", "set", userData, true);
            $form.setFormDatas({
                paymentRoadAmount : sum1,
                payedAmount : sum,
                paymentCommodityAmount : sum2
            });
        },
        shareRoadAmountToRows : function() {
            var $form = $(this);
            var $grid = $form.find(".grid-myt-purchase-purchase-receipt-inputBasic");
            if ($grid.jqGrid("isEditingMode", true)) {
                return false;
            }
            // 按照“原价金额”的比率计算更新每个行项的折扣额，注意最后一条记录需要以减法计算以修正小数精度问题
            var totalRoadAmount = $form.find("input[name='paymentRoadAmount']").val();

            var totalOriginalAmount = $grid.jqGrid('sumColumn', 'originalAmount');
            var perRoadAmount = MathUtil.div(totalRoadAmount, totalOriginalAmount, 5);

            var lastrowid = null;
            var tempRoadAmount = 0;
            var ids = $grid.jqGrid("getDataIDs");
            $.each(ids, function(i, id) {
                var rowdata = $grid.jqGrid("getRowData", id);
                if (rowdata['commodity.id'] != '') {
                    rowdata['roadAmount'] = MathUtil.mul(perRoadAmount, rowdata['originalAmount']);
                    $grid.data("gridOptions").calcRowAmount.call($grid, rowdata, 'roadAmount','false');
                    $grid.jqGrid('setRowData', id, rowdata);
                    tempRoadAmount = MathUtil.add(tempRoadAmount, rowdata['roadAmount']);
                    lastrowid = id;
                }
            });

            // 最后一条记录需要以减法计算以修正小数精度问题
            if (lastrowid) {
                var rowdata = $grid.jqGrid("getRowData", lastrowid);
                rowdata['roadAmount'] = MathUtil.sub(totalRoadAmount, MathUtil.sub(tempRoadAmount,
                        rowdata['roadAmount']));
                $grid.data("gridOptions").calcRowAmount.call($grid, rowdata, 'roadAmount','false');
                $grid.jqGrid('setRowData', lastrowid, rowdata);
            }

            $form.data("formOptions").updateTotalAmount.call($form);

        },
        bindEvents : function() {
            var $form = $(this);
            var $grid = $form.find(".grid-myt-purchase-purchase-receipt-inputBasic");
            var $grid2 = $form.find(".grid-myt-purchase-purchase-receipt-inputBasic-accountSubjects");
            
            // 从采购订单选取
            $form.find(".btn-select-purchase-order").click(
            function() {
                var $purchaseOrderId = $form.find("input[name='purchaseOrder.id']");
                var purchaseOrderId = $purchaseOrderId.val();
                if (purchaseOrderId != '') {
                    if (confirm("一个收货单只允许从单个采购订单选取，重新选取将清空当前相关数据以新选择订单数据覆盖，确认继续？")) {
                        $grid.clearGridData();
                        $grid2.clearGridData();
                        $form.data("formOptions").updateTotalAmount.call($form);
                        $form.data("formOptions").updateTotalAccountAmount.call($form);
                    }
                }

                $(this).popupDialog({ url : WEB_ROOT + '/myt/purchase/purchase-receipt!forward?_to_=selectPurchaseOrder',
                    title : '选取采购订单',
                    callback : function(data) {
                        var master = data.master;
                        var rows = data.rows;
                        var voucher = master['voucher'];
                        $purchaseOrderId.val(master.id);
                        $form.setFormDatas({
                            'externalVoucher' : master['voucher'],
                            'externalSource' : 'MYT',
                            'supplier.id' : master['supplier.id']
                        }, true);
                        $.each(rows, function(i, row) {
                            row['purchaseOrderDetail.id'] = row['id'];
                            row['quantity'] = MathUtil.sub(row['quantity'],
                                    (row['recvQuantity']));

                            // 从采购订单带的数量，隐藏，用于限制行项输入数量不能大于它
                            row['purchaseOrderQuantity'] = MathUtil.sub(
                                    row['quantity'], row['recvQuantity']);

                            $grid.data("gridOptions").calcRowAmount.call($grid, row,'amount');
                            var newid = $grid.jqGrid('insertNewRowdata', row);
                            var idx = $grid.find("tr[id='" + newid + "'] >td.jqgrid-rownum").html().trim();
                            $grid.jqGrid('setRowData', newid, {
                                subVoucher : 100 + idx * 10
                            });
                            $form.data("formOptions").updateTotalAmount.call($form);

                        });

                        $(this).ajaxJsonUrl(WEB_ROOT + "/myt/finance/payment-receipt-detail!findByPage?search['EQ_tradeReceipt.bizVoucher']="+ voucher,
                            function(data) {
                                var objects = data.content;
                                $.each( objects, function(key, row) {
                                    row['tradeReceipt.bizTradeUnit.id'] = objects[key].tradeReceipt.bizTradeUnit.id;
                                    row['tradeReceipt.bizTradeUnit.display'] = objects[key].tradeReceipt.bizTradeUnit.display;
                                    row['accountSummary.id'] = objects[key].tradeReceipt.accountSubject.id;
                                    row['accountSubject.display'] = objects[key].tradeReceipt.accountSubject.display;
                                    row['tradeReceipt.bizVoucher'] = objects[key].tradeReceipt.bizVoucher;
                                    row['tradeReceipt.voucher'] = objects[key].tradeReceipt.voucher;
                                    row['amount'] = objects[key].amount;
                                    row['costable'] = "1";
                                    row['paymentVouchers'] = objects[key].paymentVouchers;
                                    $grid2.data("gridOptions").calcRowAmount.call($grid2, row);
                                    $grid2.jqGrid('insertNewRowdata', row);
                                    $form.data("formOptions").updateTotalAccountAmount.call($form);
                                });
                            })
                    }
                })

            });

            // 从调拨单选取
            $form.find(".btn-select-commodity-stock-move").click(function() {
                var $commodityStockMoveId = $form.find("input[name='commodityStockMove.id']");
                var commodityStockMoveId = $commodityStockMoveId.val();
                if (commodityStockMoveId != '') {
                    if (confirm("不能关联多个调拨单，确认继续，将覆盖数据")) {
                        $grid.clearGridData();
                        $grid2.clearGridData();
                        $form.data("formOptions").updateTotalAmount.call($form);
                        $form.data("formOptions").updateTotalAccountAmount.call($form);
                    }else{
                        return;
                    }
                }
                $(this).popupDialog({
                    url : WEB_ROOT + '/myt/purchase/purchase-receipt!forward?_to_=selectCommodityStockMove',
                    title : '选取调拨单',
                    callback : function(data) {
                        var master = data.master;
                        
                        var StorageLocationCode = master['originStorageLocation.code']+"-";
                        var options = $form.find("select[name='supplier.id'] option");
                        options.removeAttr("selected");
                        $.each(options, function(i, option){
                            var txt = $(option).html();
                            var spid = $(option).val();
                            if(txt.substr(0, StorageLocationCode.length) == StorageLocationCode){
                                $form.setFormDatas({
                                    'supplier.id' : spid
                                }, true);
                                return false;
                            } 
                        });
                        
                        var rows = data.rows;
                        $commodityStockMoveId.val(master.id);
                        var voucher = master['voucher'];
                        $form.setFormDatas({
                            'externalVoucher' : master['logisticsNo'],
                            'externalSource' : 'MYT'
                        }, false);
                        var destinationStorageLocationId = master['destinationStorageLocation.id'];
                        $.each(rows, function(i, row) {
                            row['commodityStockMoveDetail.id'] = row['id'];
                            row['storageLocation.id'] = destinationStorageLocationId;
                            row['originalAmount'] = row['costAmount'];
                            row['price'] = row['costPrice'];
                            row['discountRate'] = 0;
                            row['quantity'] = MathUtil.sub(row['quantity'], row['inStockQuantity']);
                            row['deliveryAmount'] = 0;
                            row['discountRate'] = 0;
                            $grid.data("gridOptions").calcRowAmount.call($grid, row,'amount');
                            $grid.jqGrid('insertNewRowdata', row);
                            $form.data("formOptions").updateTotalAmount.call($form);

                        });
                        $(this).ajaxJsonUrl(WEB_ROOT + "/myt/finance/payment-receipt-detail!findByPage?search['EQ_tradeReceipt.bizVoucher']="+ voucher,
                            function(data) {
                                var objects = data.content;
                                $.each( objects, function(key, row) {
                                    row['tradeReceipt.bizTradeUnit.id'] = objects[key].tradeReceipt.bizTradeUnit.id;
                                    row['tradeReceipt.bizTradeUnit.display'] = objects[key].tradeReceipt.bizTradeUnit.display;
                                    row['accountSummary.id'] = objects[key].tradeReceipt.accountSubject.id;
                                    row['accountSubject.display'] = objects[key].tradeReceipt.accountSubject.display;
                                    row['tradeReceipt.bizVoucher'] = objects[key].tradeReceipt.bizVoucher;
                                    row['tradeReceipt.voucher'] = objects[key].tradeReceipt.voucher;
                                    row['amount'] = objects[key].amount;
                                    row['costable'] = "1";
                                    row['paymentVouchers'] = objects[key].paymentVouchers;
                                    $grid2.data("gridOptions").calcRowAmount.call($grid2, row);
                                    $grid2.jqGrid('insertNewRowdata', row);
                                    $form.data("formOptions").updateTotalAccountAmount.call($form);
                                });
                            })
                    }
                })
            });
            //扫描枪输入处理中用到的 自动填充商品行项方法
            var completeCommodity = function(item){
                var rowdata = item;
                var ids = $grid.jqGrid('getDataIDs');
                var targetRowdata = null;
                var targetRowid = null;
                $.each(ids, function(i, id) {
                    var item = $grid.jqGrid('getRowData', id);
                    if (item['commodity.sku'] == rowdata['sku']) {
                        targetRowid = id;
                        targetRowdata = item;
                        return false;
                    }
                });

                if (targetRowdata) {
                    targetRowdata.quantity = Number(targetRowdata.quantity) + 1;
                    $grid.data("gridOptions").calcRowAmount.call($grid, targetRowdata);
                    $grid.jqGrid('setRowData', targetRowid, targetRowdata);
                } else {
                    var newdata = {
                        'commodity.id' : rowdata.id,
                        'commodity.sku' : rowdata.sku,
                        'measureUnit' : rowdata.measureUnit,
                        'storageLocation.id' : rowdata['defaultStorageLocation.id'],
                        'commodity.display' : rowdata.display,
                        'discountRate' : 0,
                        'quantity' : 1,
                        'price' : rowdata.costPrice
                    }
                    $grid.data("gridOptions").calcRowAmount.call($grid, newdata);
                    $grid.jqGrid('insertNewRowdata', newdata);
                }
                $form.data("formOptions").updateTotalAmount.call($form);
            }
            // 扫描枪输入处理
            $barcodeInp = $form.find("input[name='barcode']");
            $barcodeInp.barcodeScanSupport({
                onEnter : function() {
                    var code = $(this).val();
                    if (code != '') {
                        var data = Biz.queryCacheCommodityDatas(code);
                        if (data && data.length > 0) {
                            var rowdata = data[0];
                            completeCommodity(rowdata);
                        }
                        $(this).blur().focus();
                    }
                }
            });
            // 条码框的自动提示（如果一个条码查询返回多个商品，则显示商品列表让用户进一步选取商品）
            $barcodeInp.autocomplete({
                source : function(request, response) {
                    var data = Biz.queryCacheCommodityDatas(request.term);
                    // 如果没有匹配到商品，或者只匹配到一条商品，那么不显示下拉列表
                    if(data.length < 2){
                        return response({});
                    }
                    return response(data);
                },
                minLength : 2,
                select : function(event, ui) {
                    var item = ui.item;
                    // this.value = item.display;
                    // 调用填充行项方法
                    completeCommodity(item);
                    
                    event.stopPropagation();
                    event.preventDefault();
                    return false;
                }
            });
            // 按金额自动清空分摊运费
            $form.find(".btn-delivery-by-amount").click(function() {
                $form.data("formOptions").shareRoadAmountToRows.call($form);
            });
            /*
             * // 按金额自动累加分摊运费
             * $form.find(".btn-delivery-by-amount-sum").click(
             * function() { if ($grid.jqGrid("isEditingMode",
             * true)) { return false; } //
             * 按照“原价金额”的比率计算更新每个行项的折扣额，注意最后一条记录需要以减法计算以修正小数精度问题
             * var totalDeliveryAmount =
             * $form.find("input[name='paymentDeliveryAmount']").val();
             * var totalOriginalAmount =
             * $grid.jqGrid('sumColumn', 'originalAmount'); var
             * perDeliveryAmount =
             * MathUtil.div(totalDeliveryAmount,
             * totalOriginalAmount, 5);
             * 
             * var lastrowid = null; var tempDeliveryAmount = 0;
             * var ids = $grid.jqGrid("getDataIDs"); var
             * lastDeliveryAmountByRow = 0; $.each(ids,
             * function(i, id) { var rowdata =
             * $grid.jqGrid("getRowData", id); if
             * (rowdata['commodity.id'] != '') { var
             * tempDeliveryAmountByRow =
             * MathUtil.mul(perDeliveryAmount,
             * rowdata['originalAmount']);
             * 
             * rowdata['deliveryAmount'] =
             * MathUtil.add(rowdata['deliveryAmount'],
             * tempDeliveryAmountByRow);
             * 
             * $grid.data("gridOptions").calcRowAmount.call($grid,
             * rowdata, 'deliveryAmount');
             * $grid.jqGrid('setRowData', id, rowdata);
             * tempDeliveryAmount =
             * MathUtil.add(tempDeliveryAmount,
             * tempDeliveryAmountByRow); lastrowid = id;
             * lastDeliveryAmountByRow =
             * tempDeliveryAmountByRow; } }); //
             * 最后一条记录需要以减法计算以修正小数精度问题 if (lastrowid) { var
             * rowdata = $grid.jqGrid("getRowData", lastrowid);
             * rowdata['deliveryAmount'] =
             * MathUtil.sub(rowdata['deliveryAmount'],
             * lastDeliveryAmountByRow); var
             * tempDeliveryAmountByRow =
             * MathUtil.sub(totalDeliveryAmount, MathUtil.sub(
             * tempDeliveryAmount, lastDeliveryAmountByRow));
             * rowdata['deliveryAmount'] =
             * MathUtil.add(rowdata['deliveryAmount'],
             * tempDeliveryAmountByRow);
             * $grid.data("gridOptions").calcRowAmount.call($grid,
             * rowdata, 'deliveryAmount');
             * $grid.jqGrid('setRowData', lastrowid, rowdata); }
             * 
             * $form.data("formOptions").updateTotalAmount.call($form);
             * 
             * });
             */
            $form.find("input[name='accountSubject.display']").treeselect({
                url : WEB_ROOT + "/myt/finance/account-subject!findPaymentAccountSubjects",
                callback : {
                    onSingleClick : function(event, treeId, treeNode) {
                        $form.setFormDatas({
                            'accountSubject.id' : treeNode.id,
                            'accountSubject.display' : treeNode.display
                        }, true);
                    },
                    onClear : function(event) {
                        $form.setFormDatas({
                            'accountSubject.id' : '',
                            'accountSubject.display' : ''
                        }, true);
                    }
                }
            });
        },
        preValidate : function() {
            var $form = $(this);
            /*
             * var $totalRoadAmount =
             * $form.find("input[name='totalRoadAmount']"); var
             * $paymentRoadAmount =
             * $form.find("input[name='paymentRoadAmount']"); if
             * ($totalRoadAmount.val() !=
             * $paymentRoadAmount.val()) {
             * bootbox.alert("收货单‘其他分摊费用’和‘付款成本总金额’不一致"); return
             * false; }
             */
            $form.data("formOptions").shareRoadAmountToRows.call($form);
        }
    });

    $(".grid-myt-purchase-purchase-receipt-inputBasic").data("gridOptions", {
        calcRowAmount : function(rowdata, src,isCalOriginalData) {
            // 精度问题
            // TODO
            //是否计算原始信息：单价 折扣等
            if(isCalOriginalData!='false'){
                rowdata['originalAmount'] = MathUtil.mul(rowdata['price'], rowdata['quantity']);
                if (src == 'discountAmount') {
                    rowdata['discountRate'] = MathUtil.mul(MathUtil.div(rowdata['discountAmount'], rowdata['originalAmount'],
                            5), 100);
                    rowdata['amount'] = MathUtil.sub(rowdata['originalAmount'], rowdata['discountAmount']);
                } else if (src == 'amount') {

                    rowdata['discountAmount'] = MathUtil.sub(rowdata['originalAmount'], rowdata['amount']);
                    rowdata['discountRate'] = MathUtil.div(rowdata['discountAmount'], rowdata['originalAmount'], 5) * 100;
                } else {

                    rowdata['discountAmount'] = MathUtil.div(
                            MathUtil.mul(rowdata['discountRate'], rowdata['originalAmount']), 100);
                    rowdata['amount'] = MathUtil.sub(rowdata['originalAmount'], rowdata['discountAmount']);
                }
            }
           
            // 先计算金额，在计算单价，以避免精度问题
            rowdata['costAmount'] = MathUtil.add(MathUtil.add(rowdata['amount'], rowdata['deliveryAmount']),
                    rowdata['roadAmount']);
            rowdata['costPrice'] = MathUtil.div(rowdata['costAmount'], rowdata['quantity']);

        },
        updateRowAmount : function(src) {
            var $grid = $(this);
            var rowdata = $grid.jqGrid("getEditingRowdata");
            $grid.data("gridOptions").calcRowAmount.call($grid, rowdata, src);
            $grid.jqGrid("setEditingRowdata", rowdata);
        },
        batchEntitiesPrefix : "purchaseReceiptDetails",
        url : function() {
            var pk = $(this).attr("data-pk");
            if (pk) {
                return WEB_ROOT + "/myt/purchase/purchase-receipt!purchaseReceiptDetails?id=" + pk + "&clone="
                        + $(this).attr("data-clone");
            }
        },
        colModel : [ {
            label : '所属采购单主键',
            name : 'purchaseReceipt.id',
            hidden : true,
            hidedlg : true,
            editable : true,
            formatter : function(cellValue, options, rowdata, action) {
                var pk = $(this).attr("data-pk");
                return pk ? pk : "";
            }
        }, {
            label : '拆分',
            name : 'splitBtn',
            editable : true,
            width : 75,
            editoptions : {
                dataInit : function(elem){
                    var $grid = $(this);
                    var btn = $('<button class="btn yellow" type="button">拆分</button>');
                    btn.click(function(){
                        var rowdata = $grid.jqGrid("getEditingRowdata");
                        console.info(rowdata['commodity.id']);
                        if(rowdata['commodity.id']==null || rowdata['commodity.id'].length<1){
                            alert("请先选择商品");
                            return;
                        }
                        rowdata.quantity = 0;// 当前编辑行数量置0
                        $grid.jqGrid("setEditingRowdata", rowdata);// 当前编辑行数量置0
                        $grid.jqGrid('insertNewRowdata', rowdata);// 复制一行
                    });
                    $(elem).replaceWith(btn);//文本框替换为button
                }
            }
        }, {
            label : '采购订单行项',
            name : 'purchaseOrderDetail.id',
            hidden : true,
            hidedlg : true,
            editable : true
        }, {
            label : '调货单行项',
            name : 'commodityStockMoveDetail.id',
            hidden : true,
            hidedlg : true,
            editable : true
        }, {
            label : '商品主键',
            name : 'commodity.id',
            hidden : true,
            hidedlg : true,
            editable : true
        }, {
            name : 'commodity.sku',
            hidden : true,
            hidedlg : true,
            editable : true
        }, {
            label : '行项号',
            name : 'subVoucher',
            width : 50,
            editable : true,
            editrules : {
                required : true
            },
            editoptions : {
                dataInit : function(elem) {
                    var $el = $(elem);
                    if ($el.val() == '') {
                        var $jqgrow = $el.closest(".jqgrow");
                        var idx = $jqgrow.parent().find(".jqgrow:visible").index($jqgrow);
                        $el.val(100 + idx * 10);
                    }
                }
            },
            align : 'center'
        }, {
            label : '采购(入库)商品',
            name : 'commodity.display',
            width : 200,
            editable : true,
            editrules : {
                required : true
            },
            editoptions : {
                placeholder : '输入商品信息提示选取或双击选取',
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    // 弹出框的选取回调函数
                    var selectCommodity = function(item) {
                        
                        var ids = $grid.jqGrid('getDataIDs');// 返回当前grid里所有数据的id
                        var existRowId = null;// 如果是已经选择过的商品，那么这是哪个商品的所在行行号
                        var oldQuantity = null;// 如果是已经选择过的商品，那么这是哪个商品的数量
                        for(i=0; i<ids.length; i++){
                            var row = $grid.jqGrid('getRowData', ids[i]);//获取单行数据根据ID
                            if(item['sku'] == row['commodity.sku']){
                                // SKU一致即认为是同一商品
                                existRowId = ids[i];
                                oldQuantity = row.quantity;
                                break;
                            }
                        }
                        
                        if(existRowId){
                            $grid.jqGrid("setRowData", existRowId, {
                                'quantity' : MathUtil.add(oldQuantity,1)
                            });
                            var myrowdata = $grid.jqGrid('getRowData', existRowId);//获取单行数据根据ID
                            $grid.data("gridOptions").calcRowAmount.call($grid, myrowdata);
                            $grid.jqGrid("setRowData", existRowId, myrowdata);
                        }else{
                            var myrowdata = {
                                    'commodity.sku' : item['sku'],//商品唯一性标识
                                    'commodity.id' : item.id,
                                    'price' : item.price,
                                    'measureUnit' : item.measureUnit,
                                    'commodity.display' : item.title,
                                    'storageLocation.id' : item['defaultStorageLocation.id'],
                                    'quantity' : 1,
                                    'discountRate' : 0,
                                    'roadAmount' : 0,
                                    'deliveryAmount' : 0
                            };
                            $grid.data("gridOptions").calcRowAmount.call($grid, myrowdata);
                            existRowId = $grid.jqGrid("insertNewRowdata", myrowdata);
                        }
                        
                        // 整个Form相关金额字段更新
                        var $form = $grid.closest("form");
                        $form.data("formOptions").updateTotalAmount.call($form);
                        
                        // 计算并设置行项号
                        var idx = $grid.find("tr[id='" + existRowId + "'] >td.jqgrid-rownum").html().trim();
                        $grid.jqGrid('setRowData', existRowId, {
                            subVoucher : 100 + idx * 10
                        });
                    }
                    
                    // 自动完成框的选取回调函数
                    var autocompleteSelectCommodity = function(item) {
                        
                        var ids = $grid.jqGrid('getDataIDs');// 返回当前grid里所有数据的id
                        
                        var existRowId = null;// 如果是已经选择过的商品，那么这是哪个商品的所在行行号
                        var oldQuantity = null;// 如果是已经选择过的商品，那么这是哪个商品的数量
                        for(i=0; i<ids.length; i++){
                            var row = $grid.jqGrid('getRowData', ids[i]);//获取单行数据根据ID
                            if(item['sku'] == row['commodity.sku']){
                                // SKU一致即认为是同一商品
                                existRowId = ids[i];
                                oldQuantity = row.quantity;
                                break;
                            }
                        }
                        
                        if(existRowId){
                            var myrowdata = $grid.jqGrid('getRowData', existRowId);//获取单行数据根据ID
                            alert("所选商品已存在[ "+myrowdata.subVoucher+" | "+myrowdata['commodity.display']+" ]，请直接编辑数量字段。");
                            return;
                        }else{
                            var myrowdata = {
                                    'commodity.sku' : item['sku'],//商品唯一性标识
                                    'commodity.id' : item.id,
                                    'price' : item.price,
                                    'measureUnit' : item.measureUnit,
                                    'commodity.display' : item.title,
                                    'storageLocation.id' : item['defaultStorageLocation.id'],
                                    'quantity' : 1,
                                    'discountRate' : 0,
                                    'roadAmount' : 0,
                                    'deliveryAmount' : 0
                            };
                            $grid.data("gridOptions").calcRowAmount.call($grid, myrowdata);
                            existRowId = $grid.jqGrid("setEditingRowdata", myrowdata);
                        }
                        
                        // 整个Form相关金额字段更新
                        var $form = $grid.closest("form");
                        $form.data("formOptions").updateTotalAmount.call($form);
                        
                        // 计算并设置行项号
                        var idx = $grid.find("tr[id='" + existRowId + "'] >td.jqgrid-rownum").html().trim();
                        $grid.jqGrid('setRowData', existRowId, {
                            subVoucher : 100 + idx * 10
                        });
                    }
                    
                    $elem.dblclick(function() {
                        var rowdata = $grid.jqGrid("getEditingRowdata");
                        $(this).popupDialog({
                            url : WEB_ROOT + '/myt/md/commodity!forward?_to_=selectionMore',
                            title : '选取库存商品',
                            callback : function(item) {
                                selectCommodity(item);
                            }
                        })
                        // 多选模式双击弹出选取框之后，取消当前行编辑状态
                        $grid.closest("div.ui-jqgrid-view").find(".ui-pg-div span.ui-icon-cancel").click();
                    }).autocomplete({
                        autoFocus : true,
                        source : function(request, response) {
                            var data = Biz.queryCacheCommodityDatas(request.term);
                            return response(data);
                        },
                        minLength : 2,
                        select : function(event, ui) {
                            var item = ui.item;
                            this.value = item.display;

                            autocompleteSelectCommodity(item);
                            event.stopPropagation();
                            event.preventDefault();
                            return false;
                        },
                        change : function(event, ui) {
                            if (ui.item == null || ui.item == undefined) {
                                //$elem.val("");
                                $elem.focus();
                            }
                        }
                    }).focus(function() {
                        $elem.select();
                    });
                }
            },
            align : 'left'
        }, {
            label : '收货仓库',
            name : 'storageLocation.id',
            width : 150,
            editable : true,
            editrules : {
                required : true
            },
            stype : 'select',
            searchoptions : {
                value : Biz.getStockDatas()
            }
        }, {
            label : '批次号',
            name : 'batchNo',
            width : 80,
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    $elem.keyup(function(event) {
                        $elem.val($elem.val().toUpperCase());
                    });
                }
            }
        }, {
            label : '批次过期日期',
            name : 'expireDate',
            width : 80,
            sorttype : 'date',
            editable : true
        }, {
            label : '单位',
            name : 'measureUnit',
            editable : true,
            width : 80
        }, {
            label : '数量',
            name : 'quantity',
            width : 80,
            formatter : 'number',
            editable : true,
            editrules : {
                required : true,
                number : true
            },
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    var rowid = $elem.closest("tr.jqgrow").attr("id");
                    var rowdata = $grid.jqGrid("getRowData", rowid);
                    $elem.keyup(function() {
                        /*
                         * if(rowdata['purchaseOrderDetail.id']!=
                         * undefined&&rowdata['purchaseOrderDetail.id']!=''
                         * &&$elem.val()>rowdata['purchaseOrderQuantity']){
                         * alert("数量不能大于采购订单行项数量:"+rowdata['purchaseOrderQuantity']);
                         * $elem.val(rowdata['purchaseOrderQuantity']); }
                         */
                        $grid.data("gridOptions").updateRowAmount.call($grid);
                    })
                }
            },
            summaryType : 'sum',
            responsive : 'sm'
        }, {
            label : '单价',
            name : 'price',
            width : 80,
            formatter : 'currency',
            editable : true,
            editrules : {
                required : true,
                number : true
            },
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid);
                    });
                }
            },
            responsive : 'sm'
        }, {
            label : '原始金额',
            name : 'originalAmount',
            width : 80,
            formatter : 'currency',
            editable : true,
            editoptions : {
                readonly : true
            },
            responsive : 'sm'
        }, {
            label : '折扣率(%)',
            name : 'discountRate',
            width : 80,
            formatter : 'number',
            editable : true,
            editrules : {
                number : true
            },
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);

                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid, $elem.attr("name"));
                    });
                }
            },
            responsive : 'sm'
        }, {
            label : '折扣额',
            name : 'discountAmount',
            width : 80,
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid, $elem.attr("name"));
                    });
                }
            },
            align : 'right',
            responsive : 'sm'
        }, {
            label : '折后金额',
            name : 'amount',
            width : 80,
            formatter : 'currency',
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid, $elem.attr("name"));
                    });
                }
            },
            responsive : 'sm'
        }, {
            label : '商家运费',
            name : 'deliveryAmount',
            width : 80,
            formatter : 'currency',
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    if ($elem.val() == "") {
                        $elem.val(0)
                    }
                    var $form = $elem.closest("form");
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid);
                    });
                }
            },
            responsive : 'sm'
        }, {
            label : '其他分摊费用',
            name : 'roadAmount',
            width : 80,
            formatter : 'currency',
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    if ($elem.val() == "") {
                        $elem.val(0)
                    }
                    var $form = $elem.closest("form");
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid);
                    });
                }
            },
            responsive : 'sm'
        }, {
            label : '入库成本单价',
            name : 'costPrice',
            width : 80,
            formatter : 'currency',
            editable : true,
            editoptions : {
                readonly : true
            },
            responsive : 'sm'
        }, {
            label : '入库总成本',
            name : 'costAmount',
            width : 80,
            formatter : 'currency',
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $elem = $(elem);
                    $elem.attr("readonly", true);
                }
            },
            responsive : 'sm'
        } ],
        footerrow : true,
        beforeInlineSaveRow : function(rowid) {
            var $grid = $(this);
            $grid.data("gridOptions").updateRowAmount.call($grid);
        },
        afterInlineSaveRow : function(rowid) {
            var $grid = $(this);
            // 整个Form相关金额字段更新
            var $form = $grid.closest("form");
            $form.data("formOptions").updateTotalAmount.call($form);
            
            /**
             * 在编辑行保存后移除“拆分”按钮
             */
            var rowdata = $grid.jqGrid("getRowData", rowid);
            rowdata.splitBtn = "";
            $grid.jqGrid("setRowData", rowid, rowdata);
        },
        afterInlineDeleteRow : function(rowid) {
            var $grid = $(this);
            // 整个Form相关金额字段更新
            var $form = $grid.closest("form");
            $form.data("formOptions").updateTotalAmount.call($form);
        },
        userDataOnFooter : true
    });
    $(".grid-myt-purchase-purchase-receipt-inputBasic-accountSubjects").data("gridOptions",{
        calcRowAmount : function(rowdata, src) {},
        updateRowAmount : function(src) {
            var $grid = $(this);
            var rowdata = $grid.jqGrid("getEditingRowdata");
            $grid.data("gridOptions").calcRowAmount.call($grid, rowdata, src);
            $grid.jqGrid("setEditingRowdata", rowdata);
        },
        url : function() {
            var bizVoucher = $(this).attr("data-externalVoucher");
            if (bizVoucher) {
                return WEB_ROOT + "/myt/finance/payment-receipt-detail!findByPage?search['EQ_tradeReceipt.bizVoucher']="
                        + bizVoucher;
            }
        },
        colModel : [ {
            label : '业务凭证号',
            name : 'tradeReceipt.bizVoucher',
            width : 120
        }, {
            label : '付款单凭证号',
            name : 'tradeReceipt.voucher',
            width : 150
        }, {
            name : 'tradeReceipt.bizTradeUnit.id',
            hidden : true,
            hidedlg : true,
            editable : true
        }, {
            label : '往来单位',
            name : 'tradeReceipt.bizTradeUnit.display',
            width : 120,
            align : 'left'
        }, {
            name : 'accountSubject.id',
            hidden : true,
            hidedlg : true,
            editable : true
        }, {
            label : '会计科目',
            name : 'accountSubject.display',
            width : 120,
            align : 'left'
        }, {
            label : '金额',
            name : 'amount',
            width : 80,
            formatter : 'currency',
            responsive : 'sm'
        }, {
            label : '分摊',
            name : 'costable',
            width : 30,
            editable : true,
            editoptions : {
                defaultValue : true
            },
            edittype : 'checkbox'
        }, {
            label : '关联凭证',
            name : 'paymentVouchers',
            width : 100
        }, {
            label : '付款参考信息',
            name : 'paymentReference',
            edittype : 'textarea',
            width : 150

        }, {
            label : '摘要',
            name : 'memo',
            width : 150
        } ],
        footerrow : true,
        beforeInlineSaveRow : function(rowid) {
            var $grid = $(this);
            $grid.data("gridOptions").updateRowAmount.call($grid);
        },
        afterInlineSaveRow : function(rowid) {
            var $grid = $(this);
            // 整个Form相关金额字段更新
            var $form = $grid.closest("form");
            $form.data("formOptions").updateTotalAccountAmount.call($form);
        },
        afterInlineDeleteRow : function(rowid) {
            var $grid = $(this);
            // 整个Form相关金额字段更新
            var $form = $grid.closest("form");
            $form.data("formOptions").updateTotalAccountAmount.call($form);
        },
        userDataOnFooter : true
    });
});